// pages/login/login.js
import api from "../../utils/apis.js";
import message from "../../utils/message.js"
import util from "../../utils/util.js"
let app = getApp()

Page({
  data: {
    authCode: "",
    inviteUserId: '',
    type: null,
  },

  onLoad: function(options) {
    let self = this
    if (app.globalData.inviteUserId) {
      self.setData({
        inviteUserId: app.globalData.inviteUserId
      })
    }

    try {
      wx.clearStorageSync()
    } catch (e) {}
  },

  onGotUserInfo(e) {
    let self = this;

    if (e.detail.errMsg == 'getUserInfo:fail auth deny') {
      wx.showToast({
        title: "请前往小程序设置更改授权项",
        icon: 'none'
      });
      return
    }

    app.globalData.rawData = e.detail.encryptedData;
    app.globalData.signature = e.detail.signature;
    app.globalData.iv = e.detail.iv

    wx.setStorage({
      key: 'rawData',
      data: e.detail.encryptedData
    })

    wx.setStorage({
      key: 'signature',
      data: e.detail.signature
    })

    wx.setStorage({
      key: 'iv',
      data: e.detail.iv
    })

    wx.checkSession({
      success() {
        self.wxlogin();
      },
      fail() {
        self.wxlogin();
      }
    })
  },

  wxlogin() {
    let self = this;

    wx.login({
      success(res) {
        if (res.code) {
          if (res.errMsg == "login:ok") {
            self.setData({
              authCode: res.code
            });
            self.loginAction();
          }
        } else {
          console.log("登录失败！" + res.errMsg);
        }
      }
    });
  },

  loginAction() {
    let self = this;

    let param = {
      code: self.data.authCode,
      grantType: "wechat_mini_app",
      login: '',
      rawData: app.globalData.rawData,
      signature: app.globalData.signature,
      iv: app.globalData.iv
    };
    wx.showLoading({
      title: "加载中"
    });
    wx.request({
      url: api.loginApi,
      method: "POST",
      data: param,
      header: {
        "content-type": "application/json"
      },
      success(res) {
        wx.hideLoading();
        if (res.statusCode == "200") {
          let token = res.data.id_token;
          try {
            wx.setStorageSync("authorization", token);
          } catch (e) {
            console.log(e);
          }

          wx.switchTab({
            url: '/pages/index/index?bolean=true'
          })
        } else {
          if (res.data.message == 'CODE不合法') {
            self.wxlogin()
          } else {
            message.showInfo(
              res.data.message ? res.data.message : "网络连接异常"
            );
          }
        }
      }
    });
  }
})